// pages/activity/service/service.js
var dateTimePicker = require('./dateTimePicker.js')

var util = require('../utils/util');

Page({

  data: {
    //baseinfo
    serid:'',
    name:null,
    age:null,
    //gender
    sex:[
      {
        id:'1',
        value:'男',
        checked:false
      },{
        id:'2',
        value:'女',
        checked:false,
      }
    ],
    gender:null,
    number:null,
    address:null,


    //timepicker
    dateTimeArray1: null,
    dateTime1: null,
    startYear: null,
    endYear: null,
    dateTimeArray2: null,
    dateTime2: null,
    datecurrent:null,
    starttime:'',
    finishtime:'',
    nowtime:'',

    //serviceinfo
    text1:null,
    text2:null,

   albumNam:'',
   checked:false,
   state:"",
   show:true,
   show1:false,
   showID:"",
   inputValue:"",
   label:'',
   obtnArry:[
     {
       name:"代购物品",
       num:0,
       selected:false
     },{
      name:"家政服务",
      num:1,
      selected:false
    },{
      name:"健康指导",
      num:2,
      selected:false
    },{
      name:"谈心交流",
      num:3,
      selected:false
    },{
      name:"陪伴娱乐",
      num:4,
      selected:false
    }
   ]
  },
  
  //baseinfo
  getInputValue:function(e){

    let key = e.currentTarget.dataset.name
    this.setData({
      [key]:e.detail.value
    })
    var num = e.detail.value
    if(num == 1)
      this.setData({
        gender:'男'
      })
    else
    this.setData({
      gender:'女'
    })
    console.log(this.data)
  },

  //timepicker
  onLoad: function(options) {
    var oldlist = JSON.parse(options.oldlist)
    // console.log(JSON.parse(options.oldlist))
    // console.log(oldlist.starttime.replace(/-/g, ' '))
    var startyear = oldlist.starttime.replace(/-/g, ' ').split(' ')
    var starttime = startyear[3].split(':')

    var finishyear = oldlist.finishtime.replace(/-/g, ' ').split(' ')
    var finishtime = finishyear[3].split(':')

    // console.log(parseInt(year[1]))
    // console.log(year.split(' '))
    // console.log(d.split(':'))
    
    var sex = oldlist.sergender
    var label = oldlist.label
    if(sex === "男"){
      this.data.sex[0].checked = true
    }else{
      this.data.sex[1].checked = true
    }
    if(label == '代购物品'){
      label = 0
    }else if(label == '家政服务'){
      label = 1
    }else if(label == '健康指导'){
      label = 2
    }else if(label == '谈心交流'){
      label = 3
    }else if(label == '陪伴娱乐'){
      label = 4
    }else{
      label = 5
    }

    this.data.obtnArry[label].selected = true;

    var nowdate = util.formatTime(new Date());
    this.setData({
      nowtime:nowdate
    })
    // console.log(nowdate)
    let that = this;
    // 获取完整的年月日 时分秒，以及默认显示的数组
    var obj = dateTimePicker.dateTimePicker(this.data.startYear, this.data.endYear);
    var obj1 = dateTimePicker.dateTimePicker(this.data.startYear, this.data.endYear);
    // 精确到分的处理，将数组的秒去掉
    //var lastArray = obj1.dateTimeArray.pop();
    //var lastTime = obj1.dateTime.pop();
    this.setData({
      serid:oldlist.serid,
      dateTimeArray1: obj1.dateTimeArray,//时间选择区域
      dateTime1: obj1.dateTime,//开始时间下标
      dateTimeArray2: obj1.dateTimeArray,
      dateTime2: obj1.dateTime,//结束时间下标
      datecurrent:obj1.dateTime,
      name:oldlist.sername,
      age:oldlist.serage,
      gender:oldlist.sergender,
      number:oldlist.phone,
      address:oldlist.seraddress,
      text1:oldlist.sercondition,
      text2:oldlist.content,
      sex:this.data.sex,
      label:oldlist.label,
      obtnArry:this.data.obtnArry
    });

    var startarr = [
      startyear[0]-1978,
      parseInt(startyear[1])-1,
      parseInt(startyear[2])-1,
      parseInt(starttime[0]),
      parseInt(starttime[1])
    ]
    
    var finisharr = [
      finishyear[0]-1978,
      parseInt(finishyear[1])-1,
      parseInt(finishyear[2])-1,
      parseInt(finishtime[0]),
      parseInt(finishtime[1])
    ]

    this.setData({
      dateTime1:startarr,
      dateTime2:finisharr,
      datecurrent:startarr
    })

  },

  // 选择日期时间
  changeDateTime1(e) {
    this.setData({
      dateTime1: e.detail.value,
      datecurrent:e.detail.value
    });
  },

  changeDateTimeColumn1(e) {
    var arr = this.data.dateTime1,
    dateArr = this.data.dateTimeArray1;
     
    arr[e.detail.column] = e.detail.value;
    dateArr[2] = dateTimePicker.getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]]);
   
    this.setData({
      dateTimeArray1: dateArr,
      dateTime1: arr,
      datecurrent:arr
    });

  },

//结束时间
  changeDateTime2(e) {
    this.setData({
      dateTime2: e.detail.value
    });
  },

  changeDateTimeColumn2(e) {
    var arr = this.data.dateTime2,
      dateArr = this.data.dateTimeArray2;

    arr[e.detail.column] = e.detail.value;
    dateArr[2] = dateTimePicker.getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]]);
 
    this.setData({
      dateTimeArray2: dateArr,
      dateTime2: arr

    });
  },

  //重置
reset:function(e){
    // 全局可用
  let currentPages = getCurrentPages()
  let lastRoute = currentPages[currentPages.length - 1].route
  let options = currentPages[currentPages.length - 1].options
  let optionsStr = ""
  for (let key in options) {
      optionsStr += '?' + key + '=' + options[key]
  }
  wx.redirectTo({
      url: '/' + lastRoute + optionsStr,
  })  
  },

submit:function(){
    var name = this.data.name;
    var age = this.data.age;
    var sex = this.data.gender;
    var address = this.data.address;
    var number = this.data.number;
    var text1 = this.data.text1;
    var text2 = this.data.text2;
    var datearray1 = this.data.dateTimeArray1;
    var date1 = this.data.dateTime1;
    var datearray2 = this.data.dateTimeArray2;
    var date2 = this.data.dateTime2;
    var datecurrent = this.data.datecurrent
    var starttime = datearray1[0][date1[0]]+'-'+datearray1[1][date1[1]]+'-'+datearray1[2][date1[2]]+' '
      +datearray1[3][date1[3]]+':'+datearray1[4][date1[4]]
    var finishtime = datearray1[0][date2[0]]+'-'+datearray1[1][date2[1]]+'-'+datearray1[2][date2[2]]+' '
      +datearray1[3][date2[3]]+':'+datearray1[4][date2[4]]
    this.setData({
      starttime:starttime,
      finishtime:finishtime
    })
    console.log(starttime)
    console.log(finishtime)


   
    if(name == null || age == null || sex == null || address == null || number==null || text1 == null ||text2 == null){
      wx.showToast({
        title: '有信息为空',
        icon:'error'
      })
    }
    else if(this.data.label ==""){
      wx.showToast({
        title: '请选择标签',
        icon:'error'
      })
    }else{

      var flag = 0;
      var startTime = this.data.starttime;
      var finishTime = this.data.finishtime;
      var nowTime = this.data.nowtime;
      // console.log(nowTime)
      var thisTime1 = startTime;
      var thisTime2 = nowTime;
      var thisTime3 = finishTime;
      thisTime1 = thisTime1.replace(/-/g, '/');
      thisTime2 = thisTime2.replace(/-/g, '/');
      thisTime3 = thisTime3.replace(/-/g, '/');
      var time1 = new Date(thisTime1);
      var time2 = new Date(thisTime2);
      var time3 = new Date(thisTime3);
      time1 = time1.getTime();
      time2 = time2.getTime();
      time3 = time3.getTime();
      // console.log(time1,time2,time3);
      if(time1<=time2 || time3<=time1){
        flag = 1;
      }else{
        var allTimtime = parseFloat((time3 - time1)/1000/60/60);
        if(allTimtime<=0.5||allTimtime>=24){
          flag = 2;
        }
      }
      
    /*日期判断 */  
    
      if(flag==0)
      {
        let pages = getCurrentPages(); // 当前页的数据，
        let prevPage = pages[pages.length - 2]; // 上一页的数据
        console.log(pages)
        console.log(prevPage.data.old_list)

  
        
        var arrt = {
          serid:this.data.serid,
          sername:name,
          serage:age,
          sergender:sex,
          phone:number,
          starttime:starttime,
          finishtime:finishtime,
          seraddress:address,
          content:text1,
          sercondition:text2,
          label:this.data.label
          };
          console.log(arrt)
          wx.request({
            url: 'http://127.0.0.1:8082/demo1/superadmin/updateser',
            data:JSON.stringify(arrt),
            method:'POST',
            header:{
              'Content-Type': 'application/json'
            },
            success:(res)=>{
              console.log(res)
              prevPage.onLoad()  
              wx.navigateBack({
                delta: 1,
              })
              wx.showToast({
                title: '保存成功',
                icon:'none'
              })
            }
          })
        
      } else if(flag == 1){
        wx.showToast({
          title: '日期信息有误',
          icon:'error'
        })
      }else if(flag == 2){
        wx.showToast({
          title: '日期错误（小于半小时或者大于一天）',
          icon:'none'
        })
      }
        
    }
 
  },

  //标签
    //同步输入框内容
bindKeyInput(e) {
    this.setData({
      albumName: e.detail.value
    })
},
// 选择标签并输入到label数组中
dealTap:function(e){ 
  var len = this.data.obtnArry.length 
  // console.log(e.currentTarget.dataset.index)
  var index = e.currentTarget.dataset.index
  let string = "obtnArry[" + index + "].selected";
  // const checkedicon = "obtnArry[" + e.target.dataset.index + "].selected"; 
  // console.log(!this.data.obtnArry[e.target.dataset.index].selected);
  this.setData({
    [string]: !this.data.obtnArry[e.target.dataset.index].selected
  })
  // let detailValue = this.data.obtnArry.filter(it => it.selected).map(it => it.name)
  if(index >=5 )
    {index = 5;}
  this.setData({
    label: index
  })
  for(var i=0;i<len;i++){
    if(i != index)
      {this.data.obtnArry[i].selected = false}
  }
  this.setData({
    obtnArry:this.data.obtnArry

  })
  // console.log(this.data.label)
},
addinput(e){
  this.setData({ 
    show: false,
    show1:true
  });
},

//实时获取输入框的值
bindValue(e){
  this.setData({
    inputValue: e.detail.value
  })
},
//确定按钮，添加数组达到添加标签的作用
onInputValue(){
  this.setData({ 
    show: false ,
    inputValue: this.data.inputValue
  });
  var obtnArry = this.data.obtnArry;
  console.log(this.data.inputValue)
  var value = this.data.inputValue;
    if(value == ""){
      wx.showToast({
        icon:"none",
        title: '标签内容不能为空',
      })
    }else{
      var newData = { num: obtnArry.length, name: this.data.inputValue, selected: false };
      obtnArry.push(newData);//实质是添加lists数组内容，使for循环多一次
      this.setData({
        obtnArry,
      })
      console.log(this.data.inputValue)
    }
},
//取消按钮
onCancel(){
  this.setData({ 
    show: true,
    show1:false
  });
}


})

